/**
 * Fw.util.Format
 */
Fw.util.Format = {
    /**
     * 转换为日期型
     * @param {} v
     * @return {date}
     */
    toDate: function(v){
        if(Fw.isDate(v)){
            return v;
        }
        if(Fw.isNumber(v*1)){
            v = Date.parse(v * 1);
        }
        else{
            v = Date.parse(Fw.util.Format.fmtDate(v, 'yyyy/MM/dd HH:mm:ss'));
        }
        return Fw.isNumber(v) ? new Date(v) : null;
    },
	/**
	 * 日期格式化
	 * @param {} v
	 * @param {} format
     * @return {string}
	 */
	fmtDate: function(v, format, /*private*/ parse){
		if(!v) return null;
		if (!Fw.isDate(v)) {
		    if(parse !== false){
		        var value = v;
		        v = String(v).replace(/[^0-9.]/gi, '').split('.')[0];
                switch(v.length){
                    //HHmm 2359
                    case 4:
                        return Fw.util.Format.fmtDate('19000101' + v + '00', format || Fw.util.Format.dateFormat['HM'], false);
                    //HHmmss 235959
                    case 6:
                        return Fw.util.Format.fmtDate('19000101' + v, format || Fw.util.Format.dateFormat['HMS'], false);
                    //yyyyMMdd 20151230
                    case 8:
                        return Fw.util.Format.fmtDate(v + '000000', format, false);
                    //yyyyMMddHHmmss 20151230235959
                    case 14:
                        return Fw.util.Format.fmtDate(v, format, false);
                    //long || other
                    default:
                        return Fw.util.Format.fmtDate(Fw.isNumber(value*1) ? value*1 : Date.parse(value), format, false);
                }
		    }
		    else{
		        if(v.length === 14){
		            //parse
                    v = v.substring(0, 4) + '/' + v.substring(4, 6) + '/' + v.substring(6, 8) + ' ' + v.substring(8, 10) + ':' + v.substring(10, 12) + ':' + v.substring(12, 14);
                    return Fw.util.Format.fmtDate(Date.parse(v), format, false);
		        }
		        else{
		            //long
		            v = new Date(v);
		        }
		    }
		}
		return v.format(format || Fw.util.Format.dateFormat['YMD']);
	},
    /**
     * 日期反格式化
     * @param {} v
     * @return {string}
     */
    unFmtDate: function(v){
        var format = 'yyyy/MM/dd';
        if(!Fw.isDate(v) && v){
            v = String(v).replace(/[^0-9.]/gi, '').split('.')[0];
            switch(v.length){
                //yyyyMMddHHmmss 20151230235959
                case 14:
                    format = 'yyyy/MM/dd HH:mm:ss';
                    break;
                //HHmm 2359
                case 4:
                    format = 'HH:mm';
                    break;
                //HHmmss 235959
                case 6:
                    format = 'HH:mm:ss';
                    break;
            }
        }
        return Fw.util.Format.fmtDate(v, format);
    },
    /**
     * 百分比格式化
     * @param v 原始数字
     * @param format 格式/小数点后保留位数（默认为2）
     * @return {string}
     */
    fmtPercent: function(v, format) {
        return Fw.util.Format.unFmtNumber(v, format) + '%';
    },
    /**
     * 百分比反格式化
     * @param v 百分比
     * 去逗号、去百分号
     * @return {number}
     */
    unFmtPercent: function(v) {
        return Fw.util.Format.unFmtNumber(v.replaceAll('%', ''));
    },
	/**
	 * 格式化金额
     * @param v 原始金额
     * @param decimals 小数点后保留位数（默认为2）
     * @param end 货币符号是否放在末尾（默认为false）
     * @param currencySign 货币符号（默认为￥）
     * @return {string}
	 */
    fmtAmt: function(v, decimals, end, currencySign) {
        var negativeSign = '', format = ',0';
        v = Fw.util.Format.unFmtAmt(v);
        if(!Fw.isNumber(v)){
            return v;
        }
        v = v - 0;
        if (v < 0) {
            v = -v;
            negativeSign = '-';
        }
        currencySign = Fw.isDefined(currencySign) ? currencySign || '' : Fw.util.Format.currencySign;
        decimals = Fw.isDefined(decimals) ? decimals : 2;
        format += (decimals > 0 ? '.' : '') + '0'.repeat(decimals);
        v = Fw.util.Format.fmtNumber(v, format);
        //
        if(end === true){
            return '{0}{1}{2}'.format(negativeSign, v, currencySign);
        }
        else{
            return '{0}{1}{2}'.format(negativeSign, currencySign, v);
        }
    },
    /**
     * 金额反格式化
     * 去逗号、去货币符号
     * @return {number}
     */
    unFmtAmt: function(v) {
        return Fw.isNumber(v) ? v : Fw.util.Format.unFmtNumber(String(v).replaceAll(Fw.util.Format.currencySign, ''));
    },
    /**
     * 小写金额转大写金额（默认到分）
     * @param v 原始数字/金额
     * @return {string}
     */
    fmtAmt2Chinese: function(v){
        v = Math.abs(Fw.util.Format.unFmtAmt(v));
        var number = Math.round(v * 100) / 100;
        number = number.toString(10).split('.');
        var a = number[0];
        if (a.length > 12){
            return '金额超出最大范围[999999999999.99]';
        }
        var e = '零壹贰叁肆伍陆柒捌玖';
        var num1 = '';
        var len = a.length - 1;
        for (var i = 0; i <= len; i++){
            num1 += e.charAt(parseInt(a.charAt(i))) + [['圆','万','亿'][Math.floor((len-i)/4)],'拾','佰','仟'][(len - i) % 4];
        }
        if (number.length == 2 && number[1] != '') {
            var a = number[1];
            for (var i = 0; i < a.length; i++){
                num1 += e.charAt(parseInt(a.charAt(i))) + ['角','分'][i];
            }
        }
        num1 = num1.replace(/零佰|零拾|零仟|零角/g, '零');
        num1 = num1.replace(/零{2,}/g, '零');
        num1 = num1.replace(/零(?=圆|万|亿)/g, '');
        num1 = num1.replace(/亿万/, '亿');
        num1 = num1.replace(/^圆零?/, '');
        if (num1 != '' && !/分$/.test(num1)){
            num1 += '整';
        }
        return num1;
    },
    /**
     * 数字格式化
     * @param v 原始数字
     * @param format 格式/小数点后保留位数（默认为2）
     * 0 - 123456
     * 0.00 - 123456.78
     * 0.0000 - 123456.7890
     * 0,000 - 123,456
     * 0,000.00 - 123,456.78
     * 0,0.00 - 123,456.78
     * @return {string}
     */
    fmtNumber: function(v, format) {
        if (!Fw.isDefined(format)) {
            format = '0.00';
        }
        if (Fw.isNumber(format)) {
            if(format <= 0){
                format = '0';
            }
            else{
                format = '0.' + '0'.repeat(format);
            }
        }
        
        //
        v = v * 1;
        if (!Fw.isNumber(v)) {
            return '';
        }
        var comma = ',', dec = '.', i18n = false, neg = v < 0;
        v = Math.abs(v);
        if (format.substr(format.length - 2) == '/i') {
            format = format.substr(0, format.length - 2);
            i18n = true;
            comma = '.';
            dec = ',';
        }
        var hasComma = format.indexOf(comma) != -1, psplit = (i18n ? format.replace(/[^\d\,]/g, '') : format.replace(/[^\d\.]/g, '')).split(dec);
        if (1 < psplit.length) {
            v = v.toFixed(psplit[1].length);
        } 
        else if (2 < psplit.length) {
            throw ('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
        } 
        else {
            v = v.toFixed(0);
        }
        var fnum = v.toString();
        psplit = fnum.split('.');
        if (hasComma) {
            var cnum = psplit[0], parr = [], j = cnum.length, m = Math.floor(j / 3), n = cnum.length % 3 || 3, i;
            for ( i = 0; i < j; i += n) {
                if (i != 0) {
                    n = 3;
                }
                parr[parr.length] = cnum.substr(i, n);
                m -= 1;
            }
            fnum = parr.join(comma);
            if (psplit[1]) {
                fnum += dec + psplit[1];
            }
        } 
        else {
            if (psplit[1]) {
                fnum = psplit[0] + dec + psplit[1];
            }
        }
        return (neg ? '-' : '') + format.replace(/[\d,?\.?]+/, fnum);
    },
    /**
     * 数字反格式化
     * 去逗号
     * @param v 格式化数字
     * @return {number}
     */
    unFmtNumber: function(v){
        if(Fw.isNumber(v) || !v){
            return v;
        }
        else{
            return v.replaceAll(',', '') * 1;
        }
    },
    /**
     * 帐号格式化、 添加空格分隔符
     * @param  acc {string} 账户号
     * @param mask {boolean}  是否隐藏账户  true为隐藏
     * @return {string}
     */
    fmtAcctNo: function(acc, mask){
        if (Fw.isEmpty(acc)) {
            return '';
        }
        acc = String(acc).trim(true);
        var tmpStr = '';
        if (mask) {
            acc = Fw.util.Format.fmtAcctNo(acc);//帐号格式化
            var start = acc.length - 4;
            if (start < 4) {
                start = 4;
            }
            tmpStr = tmpStr + acc.substring(0, 6) + '******' + acc.substring(start, acc.length);
        }
        else {
            while (acc.length > 4) {
                tmpStr = tmpStr + acc.substring(0, 4);
                tmpStr = tmpStr + ' ';
                acc = acc.substring(4, acc.length);
            }
            tmpStr = tmpStr + acc;
        }
        return tmpStr;
    },
    /**
     * 帐号反格式化
     * 去空格（不支持星号反显）
     * @param acc 格式化数字
     * @return {string}
     */
    unFmtAcctNo: function(acc){
        return String(acc).trim(true);
    },
    /**
     * 格式化证件类型
     * @param type
     * @returns {string}
     */
    fmtIdentityType: function(type){
        switch(String(type)){
            case 'I': return '身份证';
            case 'T': return '临时身份证';
            case 'S': return '军官证/士兵证';
            case 'P': return '护照';
            case 'L': return '营业执照';
            case 'O': return '其他有效证件';
            case 'R': return '户口簿';
            case 'H': return '港澳居民来往内地通行证';
            case 'W': return '台湾同胞来往内地通行证';
            case 'F': return '外国人居留证';
            case 'C': return '警官证';
            default: return type;
        }
    },
    /**
     * 格式化文件大小
     * @param {} size
     * @return {string}
     */
    fileSize: function(size){
        var byteLimit = 1024, kbLimit = 1048576, mbLimit = 1073741824;
        var out;
        if (size < byteLimit) {
            if (size === 1) {
                out = '1 byte';    
            } else {
                out = size + ' bytes';
            }
        } else if (size < kbLimit) {
            out = (Math.round(((size*10) / byteLimit))/10) + ' KB';
        } else if (size < mbLimit) {
            out = (Math.round(((size*10) / kbLimit))/10) + ' MB';
        } else {
            out = (Math.round(((size*10) / mbLimit))/10) + ' GB';
        }
        return out;
    },
    /**
     * 对于大于指定长度的字符串进行裁剪，增加（…）
     * @param {} v
     * @param {} length
     * @param {} [word]
     * @return {string}
     */
    ellipsis: function(v, length, word) {
        if (v && v.length > length) {
            if (word) {
                var vs = v.substr(0, length - 2),
                index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
                if (index !== -1 && index >= (length - 15)) {
                    return vs.substr(0, index) + '...';
                }
            }
            return v.substr(0, length - 3) + '...';
        }
        return v;
    }
};

/**
 * 注册到juicer
 */
Fw.each(Fw.util.Format, function(prop, fun){
    if(Fw.isFunction(fun)){
        juicer.register(prop, fun);
    }
});